Grokking Microsoft Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Microsoft Easy Problems
Buddy Strings (easy)
Solution: Buddy Strings
Can Place Flowers (easy)
Solution: Can Place Flowers
Reverse a LinkedList (easy)
Solution: Reverse a LinkedList
Maximum Number of Balloons (easy)
Solution: Maximum Number of Balloons
Binary Tree Path Sum (easy)
Solution: Binary Tree Path Sum
Pair with Target Sum (easy)
Solution: Pair with Target Sum
Buy Two Chocolates (easy)
Solution: Buy Two Chocolates
Root Equals Sum of Children (easy)
Solution: Root Equals Sum of Children
Excel Sheet Column Title (easy)
Solution: Excel Sheet Column Title
Merge Strings Alternately (easy)
Solution: Merge Strings Alternately
Min Cost Climbing Stairs (easy)
Solution: Min Cost Climbing Stairs
Plus One (easy)
Solution: Plus One
Intersection of Two Arrays (easy)
Solution: Intersection of Two Arrays
Find the Index of the First Occurrence in a String (easy)
Solution: Find the Index of the First Occurrence in a String
Merge Two Sorted Lists (easy)
Solution: Merge Two Sorted Lists
Nth Digit (medium)
Solution: Nth Digit
Restore IP Addresses (medium)
Solution: Restore IP Addresses
Find Original Array From Doubled Array (medium)
Solution: Find Original Array From Doubled Array
Reverse Words in a String II (medium)
Solution: Reverse Words in a String II
Longest Arithmetic Subsequence (medium)
Solution: Longest Arithmetic Subsequence
Matchsticks to Square (medium)
Solution: Matchsticks to Square
Score of Parentheses (medium)
Solution: Score of Parentheses
Maximum Length of a Concatenated String with Unique Characters (medium)
Solution: Maximum Length of a Concatenated String with Unique Characters
Inorder Successor in BST (medium)
Solution: Inorder Successor in BST
Distribute Coins in Binary Tree (medium)
Solution: Distribute Coins in Binary Tree
Spiral Matrix (medium)
Solution: Spiral Matrix
Delete Node in a BST (medium)
Solution: Delete Node in a BST
Sum of Subarray Minimums (medium)
Solution: Sum of Subarray Minimums
Rotate Image (medium)
Solution: Rotate Image
Combinations (medium)
Solution: Combinations
Maximum Level Sum of a Binary Tree (medium)
Solution: Maximum Level Sum of a Binary Tree
Multiply Strings (medium)
Solution: Multiply Strings
Best Time to Buy and Sell Stock II (medium)
Solution: Best Time to Buy and Sell Stock II
Largest Palindromic Number (medium)
Solution: Largest Palindromic Number
Remove Duplicate Letters (medium)
Solution: Remove Duplicate Letters
Next Permutation (medium)
Solution: Next Permutation
132 Pattern (medium)
Solution: 132 Pattern
Valid Sudoku (medium)
Solution: Valid Sudoku
Number of Islands (medium)
Solution: Number of Islands
Buildings With an Ocean View (medium)
Solution: Buildings With an Ocean View
Regular Expression Matching (hard)
Solution: Regular Expression Matching
First Missing Positive (hard)
Solution: First Missing Positive
Largest Rectangle in Histogram (hard)
Solution: Largest Rectangle in Histogram
Sliding Window Maximum (hard)
Solution: Sliding Window Maximum
Count Unique Characters of All Substrings of a Given String (hard)
Solution: Count Unique Characters of All Substrings of a Given String
Word Ladder (hard)
Solution: Word Ladder
Word Ladder II (hard)
Solution: Word Ladder II
Number of Flowers in Full Bloom (hard)
Solution: Number of Flowers in Full Bloom
Median of Two Sorted Arrays (hard)
Solution: Median of Two Sorted Arrays
Longest Valid Parentheses (hard)
Solution: Longest Valid Parentheses
Solution: Merge Two Sorted Lists

Problem Statement

Given the head of two sorted linked lists, l1 and l2.

Return a new sorted list created by merging together the nodes of the first two lists.

Examples

  1. Example 1:

    • Input:
      [1, 3, 5]
      [2, 4, 6]
      
    • Expected Output:
      [1, 2, 3, 4, 5, 6]
      
    • Justification: Merging the two sorted linked lists, node by node, results in a single sorted linked list containing all elements from both input lists.
  2. Example 2:

    • Input:
      [2, 4, 6]
      [1, 3, 5]
      
    • Expected Output:
      [1, 2, 3, 4, 5, 6]
      
    • Justification: Both lists are in ascending order; merging them node by node in ascending order gives us the sorted linked list with all elements.
  3. Example 3:

    • Input:
      [1, 2, 3]
      [4, 5, 6]
      
    • Expected Output:
      [1, 2, 3, 4, 5, 6]
      
    • Justification: As the first list contains all smaller elements, combining them results in a new list with elements from the first list followed by the second one.

Constraints:

  • The number of nodes in both lists is in the range [0, 50].
  • -100 <= Node.val <= 100
  • Both list1 and list2 are sorted in non-decreasing order.

Solution

To solve the problem, iteratively compare the nodes of the two given lists and merge them into a new sorted list. Start with a placeholder node as the head of the merged list. Compare the current nodes of both lists; whichever node has the smaller value gets appended to the merged list. Then, move forward in the list that had the smaller element. Repeat this process until one of the lists is fully traversed. At this point, simply append the remaining elements of the other list to the merged list. The placeholder head is then skipped, and the next node is returned as the head of the new, sorted merged list.

  1. Initialization:

    • Start by initializing two pointers, l1 and l2, at the heads of the first and second lists respectively.
    • Create a dummy node to keep track of the head of the merged list, and a current pointer to build the new list.
  2. Node Comparison and Merging:

    • Compare the values at l1 and l2. Append the node with the smaller value to the current pointer.
    • Move the pointer (l1 or l2) whose node has been used forward.
  3. List Traversal:

    • Continue this process of comparing, appending, and moving pointers until you reach the end of one of the lists.
    • Once one of the lists is exhausted, append the remaining nodes from the other non-empty list to current.
  4. Final Output:

    • After traversing both lists, the current pointer will have a sorted merged list attached to it. Return the next of the dummy node as the head of the merged list.

Algorithm Walkthrough

  • Start with the first nodes of the two lists, compare them and attach the smaller one to current.
  • Move forward in the list from which the node was taken.
  • Continue this process, comparing nodes and appending the smaller one to current.
  • If one of the lists is exhausted, append the remaining nodes from the other list.
  • Return the next of the dummy node as the output.

Here is the visual representation of the algorithm:

Merge Two Sorted Lists
Merge Two Sorted Lists

Code

Here is the code for this algorithm:

Java
Saved to Cloud

. . . .

Time Complexity:

  • O(n + m): The time complexity of merging two sorted linked lists is linear, where n and m are the lengths of the two input lists. In each step, we're deciding which node (from the two lists) with the smaller value should be added next to the merged list. We continue this process until one of the lists is empty, and then append the remaining list. As a result, every node is visited once, which leads to O(n + m) time complexity.

Space Complexity:

  • O(1): The space complexity is constant since we are not using any additional data structures that scale with input size. We're only using a few extra variables to keep track of the current node and the head of the merged list. All other nodes are part of the input or output, and do not count towards the space complexity. The input lists are being used to construct the output list in-place, so the algorithm is very space-efficient.
Merge Two Sorted Lists (easy)
Nth Digit (medium)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Algorithm Walkthrough

Code

Time Complexity:

Space Complexity: